package ch.cm.adnroid.cleverlearn;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import ch.cm.adnroid.cleverlearn.R.id;
import ch.cm.adnroid.cleverlearn.learn.CleverLearnLearn;
import ch.cm.adnroid.cleverlearn.load.CleverLearnLoad;
import ch.cm.adnroid.cleverlearn.model.DatabaseManager;

public class CleverLearnStart extends Activity {

    public static final String TABLE_KEY = "table";

    private LinearLayout learnButtonsLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clever_learn_start);

        learnButtonsLayout = (LinearLayout) findViewById(R.id.ll_start_learnbuttons);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SQLiteDatabase database = new DatabaseManager(this).getReadableDatabase();
        if (database != null) {

            try {
                Cursor cursor = database.query(DatabaseManager.INFO_TABLE_NAME,
                        new String[] { DatabaseManager.INFO_TABLE_NAME_COLUMN }, null, null, null, null, null);
                while (cursor.moveToNext()) {
                    Button button = new Button(this);
                    button.setOnClickListener(new LearnButtonListener());
                    button.setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.INFO_TABLE_NAME_COLUMN)));
                    learnButtonsLayout.addView(button);
                }
            } catch (Exception e) {
                Toast.makeText(this, R.string.toast_start_noquestions, Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        learnButtonsLayout.removeAllViews();
    }

    public void onButtonClick(View view) {
        switch (view.getId()) {
        case id.bu_start_load:
            startActivity(new Intent(this, CleverLearnLoad.class));
            break;
        }
    }

    private class LearnButtonListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(CleverLearnStart.this, CleverLearnLearn.class);
            Button button = (Button) v;
            intent.putExtra(TABLE_KEY, button.getText());
            startActivity(intent);
        }

    }
}
